package com.xio.cloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Author: xio
 * @Description: 服务提供者服务实现类
 * @Date: 2020/9/30 14:18
 */
@Service
public class PaymentServiceImpl {

    /**
     * 正常访问
     *
     * @param id
     * @return
     */
    public String paymentInfoOk(Integer id) {
        return "线程池:" + Thread.currentThread().getName() + ",paymentInfo_OK,id:" + id;
    }

    /**
     * 超时访问
     *
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "payment_TimeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    public String paymentInfoTimeOut(Integer id) {
        int timeNumber = 5000;
        try {
            // 暂停3秒钟
            TimeUnit.MILLISECONDS.sleep(timeNumber);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池:" + Thread.currentThread().getName() + ",paymentInfo_TimeOut,id:" + id
                + "\t" + "耗时(秒)" + timeNumber;
    }

    public String payment_TimeOutHandler(Integer id){
        return "线程池:" + Thread.currentThread().getName() + ",payment_TimeOutHandler ,id:" + id +
                "\n系统繁忙或运行报错，请稍后再来！";
    }

    /* 服务熔断 */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreakerFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value="10"),
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value="10000"),
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value="60")
    })
    public String paymentCircuitBreaker(Integer id){
        if (id < 0){
            throw new RuntimeException("***** id 不能负数");
        }
        String uuid = IdUtil.simpleUUID();
        return Thread.currentThread().getName()+"\t"+"调用成功，流水号：" + uuid;
    }

    public String paymentCircuitBreakerFallback(Integer id){
        return "id 不能负数，请稍后再试。";
    }

}
